package com.zy.dp.flyweight.example2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SecurityMgr
{

	private static SecurityMgr securityMgr = new SecurityMgr();

	private SecurityMgr()
	{

	}

	public static SecurityMgr getInstance()
	{

		return securityMgr;
	}

	private Map<String, Collection<Flyweight>> map = new HashMap<String, Collection<Flyweight>>();

	public void login(String user)
	{
		Collection<Flyweight> col = queryByUser(user);

		map.put(user, col);
	}

	public boolean hasPermit(String user, String securityEntity, String permit)

	{

		Collection<Flyweight> col = map.get(user);
		if (col == null || col.size() == 0)
		{
			System.out.println(user + "没有登录或是没有被分配任何权限");
			return false;
		}
		for (Flyweight flyweight : col)
		{
			System.out.println(flyweight);

			if (flyweight.match(securityEntity, permit))
			{
				return true;
			}

		}

		return false;

	}

	private Collection<Flyweight> queryByUser(String user)
	{

		Collection<Flyweight> col = new ArrayList<Flyweight>();
		for (String s : TestDB.colDB)
		{
			String[] ss = s.split(",");

			if (ss[0].equals(user))
			{
				Flyweight flyweight = FlyweightFactory.getInstance()
						.getFlyweight(ss[1] + "," + ss[2]);
				col.add(flyweight);
			}

		}

		return col;

	}

}
